//点击表单外就关闭表单
$(() => {
    //使body的minWidth和浏览器高度一致
    $(document.body).css('minHeight', window.innerHeight);
    //点击body使显示的表单消失
    $(document.body).on('click', function (e) {
        //点击的不是表单本身
        if ($(e.target).parents('.form-box').length === 0
            //忽略alert的关闭
            && $(e.target).parents('.tip-alert').length === 0
            //忽略所有按钮的点击
            && e.target.tagName !== 'BUTTON') {
            let form = $('.form-area .show');
            if (form.length >= 1) {
                let page = form.attr('class').split(' ')[2];

                form.removeClass(page + '-slide-down show').addClass('fade-out');
                setTimeout(() => {
                    form.addClass('hide');
                }, 500);
            }
        }
    });
});

//点击添加和修改按钮显示目标表单
$(() => {
    $('.right-contain').on('click', '.table-show tr', function (e) {
        $('.select-tr').removeClass('select-tr');
        $(this).addClass('select-tr');
    });

    $('.right-contain').on('click', 'button', function () {
        //分切按钮类
        let types = $(this).attr('class').split('-');
        //如果是添加按钮
        if (types[0] == 'add') {
            window.operation = 'add';
            $('.form-area .' + types[1]).removeClass('hide fade-out').addClass(types[1] + '-slide-down show');
            $('.form-area .' + types[1] + ' input').each((i, tag) => {
                if (i == 0) {
                    $(tag).removeAttr('readonly');
                    $(tag).val('');
                    $(tag).attr('readonly', 'readonly')
                        .css('backgroundColor', '#aaa').css('color', '#f7f7f7');

                } else {
                    $(tag).val('');
                }
            });

            //如果是修改按钮
        } else if (types[0] == 'upd') {
            window.operation = 'upd';
            let dataLine = $('.select-tr');
            //如果没有数据就不弹出修改框
            if ($('.' + types[1] + '-view tr').length < 2) {
                tip.alert('没有可修改的数据',
                    $(this).parents('.show').find('.title').text(), 'warn');
            } else if (dataLine.length == 0) {
                tip.alert('未选中行',
                    $(this).parents('.show').find('.title').text(), 'warn');
            } else {
                let form = $('.form-area .' + types[1]);
                let inputs = form.find('input');
                dataLine.children().each((i, tag) => {
                    if (i == 0) {
                        inputs.eq(0).removeAttr('readonly');
                        inputs.eq(0).val(tag.innerText);
                        inputs.eq(0).attr('readonly', 'readonly')
                            .css('backgroundColor', '#aaa').css('color', '#f7f7f7');
                    } else {
                        if (inputs.eq(i).attr('list') != undefined) {
                            $('#' + inputs.eq(i).attr('list')).children().each((j, tag2) => {
                                if (tag2.innerText == tag.innerText) {
                                    inputs.eq(i).val(tag2.value);
                                }
                            });
                        } else {
                            inputs.eq(i).val(tag.innerText);
                        }
                    }
                });
                form.removeClass('hide fade-out')
                    .addClass(types[1] + '-slide-down show');
            }
        }
    });
});

//数据获取和修改
$(() => {
    //服务器接口地址
    let server = 'http://www.fjemiot.cn/erp/';

    let titles = {
            product: ['产品编号', '品牌', '类型', '克重', '标准', '规格', '单位', '成本', '价格'],
            supplier: ['供应商编号', '公司', '地址', '联系方式'],
            employee: ['员工编号', '姓名', '联系方式', '地址', '职位', '部门'],
            customer: ['客户编号', '地址', '公司', '联系方式'],
            position: ['职位编号', '职位'],
            units: ['单位编号', '单位'],
            department: ['部门编号', '部门']
        },
        viewMessage = {
            product: {
                url: server + 'products',
                title: '产品',
                view: $('.product-view'),
                table: 'products',
                titles: titles.product,
                func: () => {
                    $('.product-view').html('');
                }
            },
            supplier: {
                url: server + 'suppliers',
                title: '供应商',
                view: $('.supplier-view'),
                table: 'Suppliers',
                titles: titles.supplier,
                func: () => {
                    $('.supplier-view').html('')
                }
            },
            employee: {
                url: server + 'employees',
                title: '员工',
                view: $('.employee-view'),
                table: 'employees',
                titles: titles.employee,
                func: null
            },
            customer: {
                url: server + 'customers',
                title: '客户',
                view: $('.customer-view'),
                table: 'customers',
                titles: titles.customer,
                func: () => {
                    $('.customer-view').html('');
                }
            },
            position: {
                url: server + 'positions',
                title: '职位',
                view: $('.position-view'),
                table: 'positions',
                titles: titles.position,
                func: null
            },
            units: {
                url: server + 'units',
                title: '单位',
                view: $('.units-view'),
                table: 'units',
                titles: titles.units,
                func: () => {
                    $('.units-view').html('');
                }
            },
            department: {
                url: server + 'departments',
                title: '部门',
                view: $('.department-view'),
                table: 'departments',
                titles: titles.department,
                func: null
            }
        };

    viewMessage.employee.func = (reply) => {
        $('.employee-view').html('');
        let array = reply['employees'];
        for (let obj of array) {
            obj['department'] = obj['department']['name'];
            obj['position'] = obj['position']['name'];
        }
    };

    viewMessage.department.func = (reply) => {
        $('.department-view').html(datalistgen('departments-list', reply['departments']));
    };

    viewMessage.position.func = (reply) => {
        $('.position-view').html(datalistgen('positions-list', reply['positions']));
    };

    for (let view in viewMessage) {
        viewMessage[view]['data'] = {pageNum:1, pageSize: 15};
        initialize(viewMessage[view]);
    }

    //数据修改
    let ajaxConfig = {
        product: {add: 'productAndStorage', upd: 'product', del: 'product'},
        supplier: {add: 'supplier', upd: 'supplier', del: 'supplier'},
        customer: {add: 'customer', upd: 'customer', del: 'customer'},
        department: {add: 'department', upd: 'department', del: 'department'},
        position: {add: 'position', upd: 'position', del: 'position'},
        employee: {add: 'employee', upd: 'employee', del: 'employee'},
        units: {add: 'unit', upd: 'unit', del: 'unit'}
    };

    $('.right-contain').on('click', 'button[class^=del]', function (e) {
        let types = e.target.classList.item(0).split('-');

        if (types[1] == 'units') types[1] = 'unit';
        let tableNo = types[1] + 'No', dataLine = $('.select-tr');

        if (dataLine.length == 1) {
            $.ajax({
                type: 'delete',
                url: server + types[1],
                data: tableNo + '=' + dataLine.children().eq(0).text(),
                dataType: 'text',
                success: (reply) => {
                    if (reply == '1001') {
                        if (types[1] == 'unit') {
                            initialize(viewMessage['units']);
                        } else {
                            initialize(viewMessage[types[1]]);
                        }
                        tip.alert('删除成功:' + dataLine.children().eq(0).text(), '删除', 'success');
                        document.body.click();
                    } else {
                        tip.alert('删除失败', '删除', 'error');
                    }
                },
                error: (reply) => {
                    console.log(JSON.parse(reply['responseText'])['message']);
                    tip.alert(JSON.parse(reply['responseText'])['message'], '删除', 'error', 5000);
                }
            });
        } else {
            tip.alert('未选中行', '删除', 'error');
        }
    });


    $('.form-area').on('click', 'button', function (e) {
        let types = e.target.classList.item(0).split('-');

        //是提交按钮，不是初始化按钮，不是删除按钮
        if (types[1] == 'submit' && types[0] != 'init') {
            if (types[0] != 'delete') {
                //获取表单数据
                let values = {}, empty = false;
                $(e.target).parent().find('input').each((i, tag) => {
                    let value = tag.value.trim();
                    if (window.operation == 'add' && value == '编号自动生成' && i == 0) value = -1;
                    values[tag.getAttribute('name')] = value;
                    if (value == ''&& i!=0) empty = true;
                });
                if (!empty) {
                    //获取接口名称
                    let config = ajaxConfig[types[0]];
                    //如果是产品要初始化区别对待
                    if (types[0] != 'product') {
                        //如果是员工要对结果进行纠错
                        if (types[0] == 'employee') {
                            values['department'] = {};
                            values['position'] = {};
                            values['department']['departmentNo'] = values['departmentNo'];
                            values['position']['positionNo'] = values['positionNo'];
                        }
                        $.ajax({
                            type: window.operation == 'add' ? 'post' : 'put',
                            url: server + config[window.operation],
                            data: JSON.stringify(values),
                            dataType: 'json',
                            contentType: 'application/json',
                            success: (reply) => {
                                if (reply == '1001') {
                                    initialize(viewMessage[types[0]]);
                                    let message = window.operation == 'add' ? '添加成功' : '修改成功';
                                    tip.alert(message, types[0], 'success');
                                    document.body.click();
                                } else {
                                    let message = window.operation == 'add' ? '添加失败' : '修改失败';
                                    tip.alert(message, types[0], 'error');
                                }
                            },
                            error: (reply) => {
                                console.log(reply['responseJSON']['message']);
                                tip.alert(reply['responseJSON']['message'], types[0], 'error', 5000);
                            }
                        });
                        //如果是产品，要初始化库存
                    } else {
                        let initValues = {}, initEmpty = false;
                        document.body.click();
                        //修改产品不用修改库存
                        if (window.operation == 'add') {
                            $('.form-area .init').removeClass('hide fade-out').addClass('fade-in show');
                            $('.form-area .init .init-submit').click(() => {
                                $('.form-area .init input').each((i, tag) => {
                                    let value = tag.value.trim();
                                    initValues[tag.getAttribute('name')] = value;
                                    if (value == '') initEmpty = true;
                                });

                                if (!initEmpty) {
                                    initValues['product'] = values;
                                    $.ajax({
                                        type: 'post',
                                        url: server + config[window.operation],
                                        data: JSON.stringify(initValues),
                                        dataType: 'json',
                                        contentType: 'application/json',
                                        success: (reply) => {
                                            if (reply == '1001') {
                                                initialize(viewMessage[types[0]]);
                                                let message = '添加成功';
                                                tip.alert(message, types[0], 'success');
                                                document.body.click();
                                            } else {
                                                let message = '添加失败';
                                                tip.alert(message, types[0], 'error');
                                            }
                                        },
                                        error: (reply) => {
                                            tip.alert(reply['responseJSON']['message'], types[0], 'error', 5000);
                                        }
                                    })
                                } else {
                                    tip.alert('输入不能为空', '初始化库存', 'warn');
                                }
                            });
                            //修改产品
                        } else {
                            $.ajax({
                                type: 'put',
                                url: server + config[window.operation],
                                data: JSON.stringify(values),
                                dataType: 'json',
                                contentType: 'application/json',
                                success: (reply) => {
                                    if (reply == '1001') {
                                        initialize(viewMessage[types[0]]);
                                        let message = '修改成功';
                                        tip.alert(message, types[0], 'success');
                                        document.body.click();
                                    } else {
                                        let message = '修改失败';
                                        tip.alert(message, types[0], 'error');
                                    }
                                },
                                error: (reply) => {
                                    tip.alert(reply['responseJSON']['message'], types[0], 'error', 5000);
                                }
                            })
                        }
                    }
                } else {
                    tip.alert('输入不能为空', types[0], 'warn');
                }
            }
        }
    });
});